package com.nimt.hqgl_idea.mapper;

import com.nimt.hqgl_idea.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;

import java.util.List;

/*实现自动装配，UserServiceImpl 中自动装配*/
@Component(value = "userMapper")
public interface UserMapper {
    @Select("select * from user where id = #{id}")
    User selectById(@Param("id") Integer userId);


    @Select("<script>" +
            "select * from user " +
            "<trim prefix = 'where' prefixOverrides = 'AND|OR'>" +
            "<if test='keywords!=null'> and concat(id,userName) like concat('%',#{keywords},'%')</if>" +
            "<if test='role!=null'> and role=#{role}</if>" +
            "</trim>" +
            " limit #{start},#{pageSize}" +
            "</script>")
    List<User> getAllUsers(@Param("start") Integer start,
                           @Param("pageSize") Integer pageSize,
                           @Param("keywords") String keywords,
                           @Param("role") String role);

    @Select("<script>" +
            "select count(1) from user " +
            "<trim prefix = 'where' prefixOverrides = 'AND|OR'>" +
            "<if test='keywords!=null'> and userName like concat('%',#{keywords},'%')</if>" +
            "<if test='role!=null'> and role=#{role}</if>" +
            "</trim>" +
            "</script>")
    int count(@Param("keywords") String keywords,
              @Param("role") String role);

    @Update("<script>" +
            "update user " +
            "<trim prefix='set' suffix='where id=#{id}' suffixOverrides=','>" +
            "<if test='userName!=null'> userName=#{userName},</if>" +
            "<if test='password!=null'> password=#{password},</if>" +
            "<if test='role!=null'> role=#{role},</if>" +
            "<if test='sex!=null'> sex=#{sex},</if>" +
            "<if test='age!=null'> age=#{age},</if>" +
            "<if test='address!=null'> address=#{address},</if>" +
            "</trim>" +
            "</script>")
    int update(User user);

    @Insert("insert into user values(null,#{userName},#{password},#{role},#{sex},#{age},#{address})")
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    void insert(User user);

    @Delete("delete from user where id = #{id}")
    int delete(Integer id);
}
